<template>
  <el-select ref="selectRef"
    v-bind="$attrs"
    :clearable="clearable"
    :multiple="multiple"
    :value-key="valueKey"
    v-model="currentVal"
  >
    <template v-if="slots.header" #header>
      <slot name="header"></slot>
    </template>
    <template v-if="slots.footer" #footer>
      <slot name="footer"></slot>
    </template>
    <template v-if="slots.prefix" #prefix>
      <slot name="prefix"></slot>
    </template>
    <template v-if="slots.empty" #empty>
      <slot name="empty"></slot>
    </template>
    <template v-if="slots.tag" #tag>
      <slot name="tag"></slot>
    </template>
    <template v-if="slots.loading" #loading>
      <slot name="loading"></slot>
    </template>
    <slot>
      <template v-if="computedOptions">
        <bs-option
          v-for="(item, index) in computedOptions"
          :key="index"
          :value="item[props.valueField]"
          :label="item[props.labelField]"
        >
        </bs-option>
      </template>
    </slot>
  </el-select>
</template>
<script setup lang="ts">
import {ref, watch, provide, computed} from 'vue'
import BsOption from './BsOption.vue'
type BsSelectProps = {
  clearable?: boolean
  options?: any[]
  labelField?: string
  valueField?: string
  modelValue: string | number | boolean | object | Array<any>
  /**option类型 */
  optionType?: string
  multiple?: boolean
  valueKey?: string
}
const slots = defineSlots<{
  default:any
  header:any
  footer:any
  prefix:any
  empty:any
  tag: any
  loading:any
}>()
const props = withDefaults(defineProps<BsSelectProps>(), {
  labelField: 'label',
  valueField: 'value',
  optionType: 'checkbox',
  clearable: true
})
const selectRef = ref()
const emit = defineEmits(['update:modalValue'])
const currentVal = ref(props.modelValue)

const computedOptions = computed(() => {
  return props.options
})
watch(() => currentVal, () => {
  emit('update:modalValue', currentVal.value)
})
watch(() => props.modelValue, () => {
  currentVal.value = props.modelValue
})

provide('selectProps', props)

defineExpose({
  focus: () => {
    selectRef.value.focus()
  },
  blur: () => {
    selectRef.value.blur()
  }
})
</script>
